package com.cgnpc.cuddemo.funcInstance.application.impl;

import cn.com.cgnpc.aep.bizcenter.appcenter.sdk.result.ApiResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cgnpc.cuddemo.funcInstance.application.ICudWinApplication;
import com.cgnpc.cuddemo.funcInstance.domain.CudFile;
import com.cgnpc.cuddemo.funcInstance.domain.CudWin;
import com.cgnpc.cuddemo.funcInstance.domain.enums.DelEnum;
import com.cgnpc.cuddemo.funcInstance.service.ICudFileService;
import com.cgnpc.cuddemo.funcInstance.service.ICudWinService;
import com.cgnpc.cuddemo.utils.IDHelper;
import com.cgnpc.cuddemo.utils.PoiUtils;
import com.cgnpc.framework.service.IBpmCenterService;
import com.cgnpc.framework.utils.HttpServlet;
import com.cgnpc.scp.common.utils.FileUtil;
import com.cgnpc.scp.common.utils.XSSFilterUtils;
import com.cgnpc.scp.manager.service.impl.DataDictServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/******************************
 * 用途说明: CudWin应用层
 * 作者姓名: PXMWRYA
 * 创建时间: 2019/11/20 14:39
 ******************************/
@Component
@Slf4j
public class CudWinApplicationImpl implements ICudWinApplication {
    @Autowired
    IBpmCenterService bpmCenterService;

    @Autowired
    ICudFileService cudFileService;

    @Autowired
    ICudWinService cudWinService;

    private static final Logger log = LoggerFactory.getLogger(DataDictServiceImpl.class);

    /**********************************
    * 用途说明: 添加中奖表数据  同时添加一个流程
    * 参数说明 params
    * 返回值说明:
    ***********************************/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertWin(String params) throws Exception{
        Map map = JSONObject.parseObject(params);
        boolean flag = false;

        CudWin win = new CudWin();
        win.setCudWinId(IDHelper.uuid());
        win.setCreateTime(new Date());
        win.setDel("0");//可用
        win.setCudWinState("0");//待兑奖

        JSONObject winObj = (JSONObject) map.get("win");

        win.setCudWinLevel(winObj.get("cudWinLevel").toString());
        win.setCudPrizeAmount(winObj.get("cudPrizeAmount").toString());
        win.setCudWinName(winObj.get("cudWinName").toString());
        win.setCudPhone(winObj.get("cudPhone").toString());

        win.setCudWinDate(winObj.getDate("cudWinDate"));
        win.setCudAwardDate(winObj.getDate("cudAwardDate"));
        win.setCudPayType(winObj.getString("cudPayType"));

        if(!StringUtils.isEmpty(winObj.get("cudWinSpeech"))){
            win.setCudWinSpeech(winObj.get("cudWinSpeech").toString());
        }
        if(!StringUtils.isEmpty(winObj.get("memo"))){
            win.setCudMemo(winObj.get("memo").toString());
        }

        //奖金性质
        if(!StringUtils.isEmpty(winObj.get("cudBonusProperty"))){
            win.setCudBonusProperty(winObj.get("cudBonusProperty").toString());
        }

        //收款账户
        if(!StringUtils.isEmpty(winObj.get("cudBankCardNo"))){
            win.setCudBankCardNo(winObj.get("cudBankCardNo").toString());
        }

        //设置流程实例相关的列表ID  可用  针对流程的formInstID
        map.put("appFormId",win.getCudWinId());

        //判断是否为保存草稿
        if(!StringUtils.isEmpty(map.get("isSaveDraft"))){
            win.setDel(DelEnum.IS_DELEGATE.getDelEnum());
//            flag = cudWinService.save(win);
            flag = true;
            if(flag){
                ApiResult apiResult = bpmCenterService.addDraft(map);
            }
        }else{
            //先处理业务
//            flag = cudWinService.save(win);
            flag = true;
            if(flag){
                //处理流程
                ApiResult apiResult = bpmCenterService.startProcess(map);
            }
        }

        //处理文件  赋值winid
        JSONArray fileArray = (JSONArray)map.get("fileList");
        //JSONObject 转 对象
        List<CudFile> fileList = new ArrayList<CudFile>();
        for (int i = 0; i < fileArray.size(); i++) {
            CudFile file = JSON.toJavaObject(fileArray.getJSONObject(i),CudFile.class);
            file.setFileWinId(win.getCudWinId());
            fileList.add(file);;
        }
        if(fileList.size() > 0){
            cudFileService.updateBatchById(fileList);
        }
        return flag;
    }

    /**********************************
    * 用途说明: 添加中奖信息  不走流程
    * 参数说明 params
    * 返回值说明:
    ***********************************/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addWin(String params) throws Exception {
        JSONObject winMap = JSONObject.parseObject(params);
        CudWin win = new CudWin();
        win.setCudWinId(IDHelper.uuid());
        win.setCreateTime(new Date());
        win.setDel("0");//可用
        win.setCudWinState("0");//待兑奖

        win.setCudWinLevel(winMap.get("cudWinLevel").toString());
        win.setCudPrizeAmount(winMap.get("cudPrizeAmount").toString());
        win.setCudWinName(winMap.get("cudWinName").toString());
        win.setCudPhone(winMap.get("cudPhone").toString());
        win.setCudWinDate(winMap.getDate("cudWinDate"));
        win.setCudAwardDate(winMap.getDate("cudAwardDate"));
        win.setCudPayType(winMap.getString("cudPayType"));

        if(!StringUtils.isEmpty(winMap.get("cudWinSpeech"))){
            win.setCudWinSpeech(winMap.get("cudWinSpeech").toString());
        }
        if(!StringUtils.isEmpty(winMap.get("memo"))){
            win.setCudMemo(winMap.get("memo").toString());
        }

        //奖金性质
        if(!StringUtils.isEmpty(winMap.get("cudBonusProperty"))){
            win.setCudBonusProperty(winMap.get("cudBonusProperty").toString());
        }

        //收款账户
        if(!StringUtils.isEmpty(winMap.get("cudBankCardNo"))){
            win.setCudBankCardNo(winMap.get("cudBankCardNo").toString());
        }

        //处理文件  赋值winid
        JSONArray fileArray = (JSONArray)winMap.get("fileList");
        //JSONObject 转 对象
        List<CudFile> fileList = new ArrayList<CudFile>();
        for (int i = 0; i < fileArray.size(); i++) {
            CudFile file = JSON.toJavaObject(fileArray.getJSONObject(i),CudFile.class);
            file.setFileWinId(win.getCudWinId());
            fileList.add(file);;
        }
        if(fileList.size() >0){
            cudFileService.updateBatchById(fileList);
        }
        return cudWinService.save(win);
    }

    /**********************************
    * 用途说明: 保存兑奖信息
    * 参数说明 params
    * 返回值说明:
    ***********************************/
    @Override
    public boolean saveWin(String params) {
        //判断上传的文件是否有 新增 和 删除
        JSONObject winMap = JSONObject.parseObject(params);
        String winId = winMap.get("cudWinId").toString();
        CudWin win = cudWinService.getById(winId);
        if(win != null){
            win.setCudWinLevel(winMap.get("cudWinLevel").toString());
            win.setCudPrizeAmount(winMap.get("cudPrizeAmount").toString());
            win.setCudWinName(winMap.get("cudWinName").toString());
            win.setCudPhone(winMap.get("cudPhone").toString());

            win.setCudWinDate(winMap.getDate("cudWinDate"));
            win.setCudAwardDate(winMap.getDate("cudAwardDate"));
            win.setCudPayType(winMap.getString("cudPayType"));

            if(!StringUtils.isEmpty(winMap.get("cudWinSpeech"))){
                win.setCudWinSpeech(winMap.get("cudWinSpeech").toString());
            }
            if(!StringUtils.isEmpty(winMap.get("memo"))){
                win.setCudMemo(winMap.get("memo").toString());
            }

            //奖金性质
            if(!StringUtils.isEmpty(winMap.get("cudBonusProperty"))){
                win.setCudBonusProperty(winMap.get("cudBonusProperty").toString());
            }

            //收款账户
            if(!StringUtils.isEmpty(winMap.get("cudBankCardNo"))){
                win.setCudBankCardNo(winMap.get("cudBankCardNo").toString());
            }
            win.setUpdateTime(new Date());

            //处理文件
            //处理文件  赋值winid
            JSONArray fileArray = (JSONArray)winMap.get("fileList");
            //JSONObject 转 对象
            List<CudFile> fileList = new ArrayList<CudFile>();
            for (int i = 0; fileArray != null && i < fileArray.size(); i++) {
                CudFile file = JSON.toJavaObject(fileArray.getJSONObject(i),CudFile.class);
                if(StringUtils.isEmpty(file.getFileWinId())){
                    file.setFileWinId(win.getCudWinId());
                    fileList.add(file);;
                }
            }
            if(fileList.size() >0 ){
                cudFileService.updateBatchById(fileList);
            }
            return cudWinService.updateById(win);
        }else{
            return false;
        }

    }

    /**********************************
    * 用途说明: 获取得奖列表
    * 参数说明 params
    * 返回值说明:
    ***********************************/
    @Override
    public IPage<CudWin> getWinList(String params) {
        Map map = JSONObject.parseObject(params);
        String searchType = map.get("searchType").toString();
        Integer pageIndex = Integer.parseInt(map.get("pageIndex").toString());
        Integer pageSize = Integer.parseInt(map.get("pageSize").toString());
        QueryWrapper<CudWin> queryWrapper = new QueryWrapper<>();
        if("0".equals(searchType)){
            //不带条件搜索
        }else if("1".equals(searchType)){
            //普通搜索  获奖者名称
            if(!StringUtils.isEmpty(map.get("keyWord"))){
                queryWrapper.like("cud_win_name",map.get("keyWord"));
            }

        }else if("2".equals(searchType)){
            //高级搜索
            if(!StringUtils.isEmpty(map.get("winLevel"))){
                queryWrapper.eq("cud_win_level",map.get("winLevel"));
            }
            if(!StringUtils.isEmpty(map.get("prizeAmount"))){
                queryWrapper.like("cud_prize_amount",map.get("prizeAmount"));
//                queryWrapper.eq("cud_prize_amount",map.get("prizeAmount"));
            }
            if(!StringUtils.isEmpty(map.get("winName"))){
                queryWrapper.like("cud_win_name",map.get("winName"));
//                queryWrapper.eq("cud_win_name",map.get("winName"));
            }
            if(!StringUtils.isEmpty(map.get("winState"))){
                queryWrapper.eq("cud_win_state",map.get("winState"));
            }
            if(!StringUtils.isEmpty(map.get("winDate"))){
                //保存的是开始时间和结束时间  前台设置value-format="yyyy-MM-dd"不存在8小时时差
                JSONArray array = (JSONArray)map.get("winDate");
                String beginTime = array.get(0).toString();
                String endTime = array.get(1).toString();
                queryWrapper.between("cud_win_date",beginTime,endTime);
            }
        }
        queryWrapper.eq("del","0");
        queryWrapper.orderByDesc("createTime");
        IPage<CudWin> page = new Page<>();
        page.setCurrent(pageIndex);
        page.setSize(pageSize);
        //查询数据库
        page = cudWinService.page(page,queryWrapper);

        return page;
    }

    /**********************************
    * 用途说明: 逻辑删除
    * 参数说明 winId
    * 返回值说明:
    ***********************************/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delWin(String winId) {
        boolean flag = false;
        CudWin win = cudWinService.getById(winId);
        if(win != null){
            win.setDel("1");
            flag = cudWinService.updateById(win);
            //撤回流程
            return flag;
        }else{
            //未找到id匹配的对象
//            throw new Exception("未找到id匹配的对象");
            return flag;
        }
    }

    /**********************************
    * 用途说明: 通过流程实例的procGuid 来匹配 信息
    * 参数说明 id
    * 返回值说明:
    ***********************************/
    @Override
    public CudWin getWinDetailsByProcInfo(String id) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("cud_proc_ins",id);
        CudWin win = cudWinService.getOne(qw);
        return win;
    }

    /**********************************
    * 用途说明: 改变中奖中台
    * 参数说明 id
    * 返回值说明:
    ***********************************/
    @Override
    public boolean updateCudWinState(String id) {
        boolean flag = false;
        CudWin win = cudWinService.getOne(new QueryWrapper<CudWin>().eq("cud_win_id",id));
        if(win != null){
            win.setCudWinState("1");
            flag = cudWinService.updateById(win);
        }

        return flag;
    }

    /**********************************
    * 用途说明: 批量删除
    * 参数说明 params
    * 返回值说明:
    ***********************************/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDelWin(String params) {
        boolean flag =false;
        JSONObject map = JSONObject.parseObject(params);
        JSONArray array = (JSONArray) map.get("objs");
        List<CudWin> winList = new ArrayList<CudWin>();
        for (int i = 0; i < array.size(); i++) {
            CudWin win = JSON.toJavaObject(array.getJSONObject(i),CudWin.class);
            win.setDel("1");
            winList.add(win);
        }
        if(winList.size() > 0 ){
            flag = cudWinService.updateBatchById(winList);
        }
        return flag;
    }

    /**********************************
    * 用途说明: 删除业务数据以及草稿
    * 参数说明 paramsMap
    * 返回值说明:
    ***********************************/
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteWinAndMyDraft(Map paramsMap) throws Exception{
        boolean flag = false;
//        String formId = paramsMap.get("formNo").toString();
//        flag = cudWinService.removeById(formId);
        //在删除文件数据和我的草稿
        flag = true;
        if(flag){
            bpmCenterService.deleteMyDraft(paramsMap);
        }
        return flag;
    }

    /**********************************
    * 用途说明: 修改表单数据以及草稿
    * 参数说明 paramsMap
    * 返回值说明:
    ***********************************/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveWinAndDraft(Map paramsMap) throws Exception {
        boolean flag = false;
        HashMap obj = (HashMap) paramsMap.get("win");
        String winId = obj.get("cudWinId").toString();
        paramsMap.put("appFormId",winId);
        String paramsWin = JSONObject.toJSONString(obj);
        flag = saveWin(paramsWin);//1 修改业务表单数据
        bpmCenterService.updateDraft(paramsMap);//2 修改草稿

        return flag;
    }


    /**********************************
    * 用途说明: 从草稿状态恢复到可用
    * 参数说明 id
    * 返回值说明:
    ***********************************/
    public boolean recoverWinState(String id){
        CudWin win = cudWinService.getById(id);
        win.setDel(DelEnum.IS_USE.getDelEnum());
        return cudWinService.updateById(win);
    }

    /**********************************
    * 用途说明: 提交业务数据以及草稿  存在草稿的情况  业务数据改变状态即可
    * 参数说明 params
    * 返回值说明:
    ***********************************/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean commitWinAndDraft(String params) throws Exception {
        Map map = JSONObject.parseObject(params);
        boolean flag = false;
        JSONObject winObj = (JSONObject) map.get("win");
        String winId = winObj.get("cudWinId").toString();//win 主键
        flag = saveWin(JSON.toJSONString(winObj));
        recoverWinState(winId);
        map.put("appFormId",winId);
        if(flag){
            bpmCenterService.startProcess(map);
            bpmCenterService.deleteMyDraft(map);
            return flag;
        }else{
            throw new Exception("保存获奖表失败!");
        }
    }

    /**********************************
    * 用途说明: 导出业务Excel数据
    * 参数说明 paramsMap
    * 返回值说明:
    ***********************************/
    @Override
    public void exportWinExcel(Map paramsMap) throws Exception {
        List<CudWin> winList = null;
        if(!StringUtils.isEmpty(paramsMap.get("objs"))){
            //说明是选中
            winList = getWinListByWins(paramsMap);
        }else{
            //说明没选中，按条件进行导出
            winList = getWinListNoPage(paramsMap);
        }
        String[] title = {"中奖等级","奖金额度","获奖者姓名","获奖感言","兑奖状态","中奖日期"};
        String fileName = "获奖名单表" + System.currentTimeMillis() + ".xls";
        String sheetName = "获奖名单表";
        exportExcel(winList, fileName, sheetName, title);
    }

    /**********************************
    * 用途说明: 获取列表数据  不分页  但有查询条件
    * 参数说明 paramsMap
    * 返回值说明:
    ***********************************/
    @Override
    public List<CudWin> getWinListNoPage(Map paramsMap) throws Exception {
        String searchType = paramsMap.get("searchType").toString();
        QueryWrapper<CudWin> queryWrapper = new QueryWrapper<>();
        if("0".equals(searchType)){
            //不带条件搜索
        }else if("1".equals(searchType)){
            //普通搜索  获奖者名称
            if(!StringUtils.isEmpty(paramsMap.get("keyWord"))){
                queryWrapper.like("cud_win_name",paramsMap.get("keyWord"));
            }
        }else if("2".equals(searchType)){
            //高级搜索
            if(!StringUtils.isEmpty(paramsMap.get("winLevel"))){
                queryWrapper.eq("cud_win_level",paramsMap.get("winLevel"));
            }
            if(!StringUtils.isEmpty(paramsMap.get("prizeAmount"))){
                queryWrapper.like("cud_prize_amount",paramsMap.get("prizeAmount"));
            }
            if(!StringUtils.isEmpty(paramsMap.get("winName"))){
                queryWrapper.like("cud_win_name",paramsMap.get("winName"));
            }
            if(!StringUtils.isEmpty(paramsMap.get("winState"))){
                queryWrapper.eq("cud_win_state",paramsMap.get("winState"));
            }
            if(!StringUtils.isEmpty(paramsMap.get("winDate"))){
                //保存的是开始时间和结束时间  前台设置value-format="yyyy-MM-dd"不存在8小时时差
                JSONArray array = (JSONArray)paramsMap.get("winDate");
                String beginTime = array.get(0).toString();
                String endTime = array.get(1).toString();
                queryWrapper.between("cud_win_date",beginTime,endTime);
            }
        }
        queryWrapper.eq("del","0");
        queryWrapper.orderByDesc("createTime");
        //查询数据库
        List<CudWin> winList = cudWinService.list(queryWrapper);
        return winList;
    }

    /**********************************
    * 用途说明: 获取列表
    * 参数说明 paramsMap
    * 返回值说明:
    ***********************************/
    @Override
    public List<CudWin> getWinListByWins(Map paramsMap) throws Exception {
        List<HashMap> list = (List<HashMap>) paramsMap.get("objs");

        List<String> idList = new ArrayList<>();
        list.forEach(map -> {
            idList.add(map.get("cudWinId").toString());
        });
        Collection<CudWin> winCollection= cudWinService.listByIds(idList);
        List<CudWin> winList = (List)winCollection;
        return winList;
    }

    /**********************************
    * 用途说明: 导出Excel
    * 参数说明 list
    * 参数说明 fileName
    * 参数说明 sheetName
    * 参数说明 titles
    * 返回值说明:
    ***********************************/
    public void exportExcel(List<CudWin> list,String fileName,String sheetName,String[] titles){
        String[][] content = new String[list.size()][titles.length];
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < list.size(); i++) {
            CudWin win = list.get(i);
            content[i][0] = (win.getCudWinLevel().equals("1")? "一等奖":win.getCudWinLevel().equals("2")? "二等奖":"三等奖");
            content[i][1] = win.getCudPrizeAmount();
            content[i][2] = win.getCudWinName();
            content[i][3] = win.getCudWinSpeech();
            if (StringUtils.isEmpty(win.getCudWinState())){
                content[i][4] = "";
            }else{
                content[i][4] = win.getCudWinState().equals("0")? "待兑奖":"已兑奖";
            }
            if (StringUtils.isEmpty(win.getCudWinDate())){
                content[i][5] = "";
            }else{
                content[i][5] = sdf.format(win.getCudWinDate());
            }
        }
        HSSFWorkbook wb = PoiUtils.getHSSFWorkbook(sheetName,titles,content,null);
        OutputStream os = null;
        try{
            HttpServletResponse response = HttpServlet.getResponse();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel");
            //前端好像获取不到filename
            response.setHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**********************************
    * 用途说明: 导入excel  批量新增
    * 参数说明 file
    * 返回值说明:
    ***********************************/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean upExcelFile(MultipartFile file) throws Exception {
        InputStream is = file.getInputStream();
        List<CudWin> winList = new ArrayList<>();
        boolean flag = false;
        try{
            Workbook workbook = WorkbookFactory.create(is);
            handleExcel(winList,workbook);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            is.close();
        }
        flag = cudWinService.saveBatch(winList);
        return flag;
    }

    /**********************************
     * 用途说明: 处理excel
     * 参数说明 file
     * 返回值说明:
     ***********************************/
    void handleExcel(List<CudWin> winList,Workbook workbook) throws Exception{
        if(workbook == null){
            throw new Exception("Excel工作簿为空！");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            sheet = workbook.getSheetAt(i);
            if (sheet == null) {
                continue;
            }
            int sheetNum = sheet.getLastRowNum();
            if(sheetNum < 8){
                throw new Exception("导入数据为空");
            }
            //遍历当前sheet中的所有行
//            for (int j = 8; j <= sheetNum ; j++) {
//                row = sheet.getRow(j);
//                if (row == null ) {
//                    continue;
//                }
//                CudWin win = new CudWin();
//                //把每个单元格的值付给对象的对应属性
//                if(row.getCell(0) != null){
//                    row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
//                    win.setCudWinLevel(row.getCell(0).toString());
//                }else{
//                    throw new Exception("导入的第"+(j + 1)+"行中奖等级不存在");
//                }
//                if(row.getCell(1) != null){
//                    row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
//                    win.setCudPrizeAmount(row.getCell(1).toString());
//                }else{
//                    throw new Exception("导入的第"+(j + 1)+"行奖金额度不存在");
//                }
//                if(row.getCell(2) != null){
//                    row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
//                    win.setCudWinName(row.getCell(2).toString());
//                }else{
//                    throw new Exception("导入的第"+(j + 1)+"行获奖者姓名不存在");
//                }
//                if(row.getCell(3) != null){
//                    row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
//                    win.setCudPhone(row.getCell(3).toString());
//                }else{
//                    throw new Exception("导入的第"+(j + 1)+"行联系方式不存在");
//                }
//                if(row.getCell(4) != null){
//                    win.setCudWinDate(DateUtils.dateTime("yyyy-MM-dd",row.getCell(4).toString()));
//                }else{
//                    throw new Exception("导入的第"+(j + 1)+"行中奖日期不存在");
//                }
//                if(row.getCell(5) != null){
//                    win.setCudAwardDate(DateUtils.dateTime("yyyy-MM-dd",row.getCell(5).toString()));
//                }else{
//                    throw new Exception("导入的第"+(j + 1)+"行发奖日期不存在");
//                }
//                if(row.getCell(6) != null){
//                    row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
//                    win.setCudPayType(row.getCell(6).toString());
//                }else{
//                    throw new Exception("导入的第"+(j + 1)+"行收款方式不存在");
//                }
//                if(row.getCell(7) != null){
//                    row.getCell(7).setCellType(Cell.CELL_TYPE_STRING);
//                    win.setCudBonusProperty(row.getCell(7).toString());
//                }
//                if(row.getCell(8) != null){
//                    row.getCell(8).setCellType(Cell.CELL_TYPE_STRING);
//                    win.setCudBankCardNo(row.getCell(8).toString());
//                }
//                if(row.getCell(9) != null){
//                    row.getCell(9).setCellType(Cell.CELL_TYPE_STRING);
//                    win.setCudWinState(row.getCell(9).toString());
//                }else{
//                    throw new Exception("导入的第"+(j + 1)+"行兑奖状态不存在");
//                }
//                if(row.getCell(10) != null){
//                    row.getCell(8).setCellType(Cell.CELL_TYPE_STRING);
//                    win.setCudWinSpeech(row.getCell(10).toString());
//                }
//                if(row.getCell(11) != null){
//                    row.getCell(8).setCellType(Cell.CELL_TYPE_STRING);
//                    win.setCudMemo(row.getCell(11).toString());
//                }
//                win.setCudWinId(IDHelper.uuid());
//                win.setCreateTime(new Date());
//                win.setDel("0");
//                winList.add(win);
//            }
        }
    }

    /**********************************
     * 用途说明: 下载导入模板
     * 参数说明 file
     * 返回值说明:
     ***********************************/
    @Override
    public void uploadTemp() throws Exception {
        //两种方式 1、自己构建excel 2、下载对应的模板
//        File file = new File("src/main/resources/upfileTemplate/template.xlsx");
//        FileInputStream inputStream = new FileInputStream(file);
        log.debug("。。。下载文件中的对应模板，通过IO流。。。");
        OutputStream out = null;
        InputStream inputStream = null;
        byte[] buff = new byte[2048];

        try{
            log.debug("。。。进入try中。。。");
            String path = this.getClass().getClassLoader().getResource("").getPath();
            File file = new File(path+"upfileTemplate/template.xlsx");
            file = FileUtil.formatSafeFileWithDownloadFile(file);
            inputStream = new FileInputStream(file);
            String filename=file.getName();
            filename= XSSFilterUtils.cleanXSS(file.getName());
            if(inputStream != null  && inputStream.available() != 0){
                log.debug("...输入流存在...");
            }

            log.debug("。。。获取inputStream。。。");
            HttpServletResponse response = HttpServlet.getResponse();
            log.debug("。。。获取response。。。");
            out = response.getOutputStream();
            log.debug("。。。获取out。。。");
            response.setCharacterEncoding("UTF-8");
            log.debug("。。。设置CharacterEncoding。。。");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            //前端好像获取不到filename
            log.debug("。。。设置ContentType。。。");
            response.setHeader("Content-Disposition", "attachment;filename="+ new String("template.xlsx".getBytes("utf-8"), "ISO8859-1"));
            log.debug("。。。设置Heade1。。。");
//            response.setHeader("Content-Length",String.valueOf(IOUtils.cop));
            log.debug("。。。设置Heade2。。。");
            int num = -1;
            log.debug("。。。IO流写入准备。。。");
            while((num = inputStream.read(buff)) != -1){
                out.write(buff,0,num);
            }
            out.flush();
            out.close();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(inputStream != null){
                inputStream.close();
            }
            if(out != null){
                out.flush();
                out.close();
            }
        }
        log.debug("完成文件模板下载");

    }
}